// let utils = require('../../../../utils/util');
const { http } = require('../../../../utils/apiutils.js');
import { input } from '../../../../utils/tools'
const util = require("../../../../utils/util")
import { formatTime, formatTime1 } from '../../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchQuery:{
      content:'',
      type:'1'
    },
    img: [],
    img1: [],
    fileListImg: [],
    fileListImg1: [],
    allWork: [{
      key: '需求方',
      value: 1
    }, {
      key: '供给方',
      value: 2
    }],
    checked: true,
    form: {
      type:2,
      name:'',
      phone:'',
      userId:'',
      place:'',
      assistanceId:'',
      content:'',
      id:0,
    },
    loading: false,
    mshow: false,
    type: '',
    firstfive: [],
    dataList: [],
    isCanDraw: false,
    obj: {},
    bgImg: 'http://linghuoimage.xbbzp.com/FtSQneu0FbMtK5QvJhAWG5_SqvlK',
    code_img: 'http://linghuoimage.xbbzp.com/Fs2WnGKVDZPvdCAnFqhe2y3UrGK7',
    lookdata: {},
    back: false,
    num1: 0,// 发布数
    num2: 0, // 帮助数
    currentDate: new Date().getTime(),
    datetime: false,
    tabs:[
      {
        title:'求助信息',
        name:1
      },
      {
        title:'帮助信息',
        name:2
      }
    ],
    tabActive:1,
    xieyi:false,
    checked:true,
    info:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.isGetSetting()
    this.setData({
      ['form.id']:options.id,
      ['form.assistanceId']:options.id
    })
  },
  deletaImg: function (e) {
    //  console.log("-----",e);
    let index = e.detail.index;
    this.data.fileListImg.splice(index, 1);
    this.setData({
      fileListImg: this.data.fileListImg,
    })
  },


  input(event) {
    input.bind(this)(event)
  },
  verify() {
    let params = JSON.parse(JSON.stringify(this.data.form));
    if (this.data.loading) return;
    this.data.loading = true;
    if(!params.title) {
      wx.showToast({
        title: '名称不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.name) {
      wx.showToast({
        title: '联系人不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.phone) {
      wx.showToast({
        title: '电话不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.place) {
      wx.showToast({
        title: '地址不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
    if(!params.content) {
      wx.showToast({
        title: '内容不能为空',
        icon: "none"
      })
      this.data.loading = false;
      return false;
  } 
  if(this.data.fileListImg.length > 0){
    this.upDataFile(this.data.fileListImg, 0, 1);
    return false;
  }else{
    this.submit()
  }
  },
  dingyue() {
    this.verify();
  },
  submit() {
    wx.showLoading({
      mask: true
    })
    let params = JSON.parse(JSON.stringify(this.data.form));
    params.images = this.data.img.join(',')
    params.userId  =getApp().globalData.userInfo.id
    params.avatar  =getApp().globalData.userInfo.avatar
    var that = this;
      console.log("--保存信息--")
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      http.saveVolunteer(params,
        function (res) {
          wx.hideLoading()
          if (res.code == 0) {
            wx.navigateBack({
              delta:1
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })
      this.data.loading = false;
    wx.hideLoading({})
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    if(file.size>5000000) {
      // 限制文件 5M以内
      wx.showToast({
        title: '文件过大，请重新选择',
        icon:"none"
      })
      return
    }
    if (file.type == "image") {
      file.isNew = true;
      this.setData({
        fileListImg: [...this.data.fileListImg, file],
      })
    } else {
      wx.showToast({
        title: '请上传图片文件',
      })
    }
  },
  
  upDataFile(data, index, type) {
    let item = data[index];
    console.log("-----", item);
    var that = this;
    var p = {
      url: item.url,
      name: "file",
      formData: {},
    }
    wx.showLoading({ mask: true })
    http.upDataFile(p,
      function (res) {
        console.log("---上传图片-", res);
        wx.hideLoading({
          success: (res) => { },
        })
        if (res.code == 0) {
          if (type == 1) {
            that.data.img.push(res.data);
            if (index == data.length - 1) {
              that.submit()
            } else {
              console.log("--继续执行--", index, data.length - 1);
              that.upDataFile(data, index + 1, type)
            }
          } else if(type == 2){
            that.data.img1.push(res.data);
            if (index == data.length - 1) {
              that.submit()
              that.data.loading = false;
            }
          }else {
            wx.showToast({
              title: res.message,
              icon: "nene",
            })
            that.data.loading = false;
          }
        }
      },
      function (err) {
        wx.hideLoading()
        that.data.loading = false;
      })
  },
  isGetSetting() {
    // 判断用户是否授权
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          lat:res.latitude,
          lng:res.longitude,
        })
        console.log("-----用户位置信息--", res)
      },
      fail: function (res) {
        wx.showModal({
          title: '获取当前定位',
          content: '请打开设置，允许小程序使用位置信息',
          cancelText: '不允许',
          confirmText: '打开设置',
          success(res1) {
            if (res1.confirm) {
              wx.openSetting({
                withSubscriptions: true,
                success(res) {
                  if (res.authSetting['scope.userLocation']) {
                    wx.nextTick(() => {
                      that.isGetSetting();
                    })
                  }
                }
              })
            }
          },
          fail(err) {
            console.log(err)
          }
        })
        that.getList()
      },
    })
  },
  getLocation() {
    let _this = this;
    wx.chooseLocation({
      success(res) {
        console.log(res)
        _this.setData({
          ['form.lat']:res.latitude,
          ['form.lng']:res.longitude,
          ['form.place']: res.address + ' ' + res.name
        })
      }
    })
  },
})